package com.weseal.dry.web;

import com.weseal.dry.config.RootConfig;
import com.weseal.dry.config.WebConfig;
import org.apache.logging.log4j.web.Log4jServletContextListener;
import org.apache.logging.log4j.web.Log4jServletFilter;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.FrameworkServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import java.util.EnumSet;

/**
 * @title
 * @description
 * @usage
 * @copyright Copyright 2014  rrmj Corporation. All rights reserved.
 * @company 上海众多美网络科技有限公司
 * @author weseal
 * @create 2018/3/27
 */
public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class<?>[]{RootConfig.class};
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class[]{WebConfig.class};
	}

	@Override
	protected String[] getServletMappings() {
		return new String[]{"/"};
	}


	@Override
	protected void customizeRegistration(ServletRegistration.Dynamic registration) {
		super.customizeRegistration(registration);
//		registration.setMultipartConfig(new MultipartConfigElement("/tmp/spittl/upload"));
	}

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
		super.onStartup(servletContext);
		//添加servlet
//		ServletRegistration.Dynamic servlet = servletContext.addServlet("",)
//		servlet.addMapping()
		// 添加拦截器
//		FilterRegistration.Dynamic filter = servletContext.addFilter();
//		filter.addMappingForUrlPatterns(null,false,"/");
		// 添加监听器
//		servletContext.addListener();
		servletContext.setInitParameter("log4jConfigLocation","class:log4j.properties");
		servletContext.addListener(Log4jServletContextListener.class);

		FilterRegistration.Dynamic log4jFilter = servletContext.addFilter("log4jFilter", Log4jServletFilter.class);
		log4jFilter.addMappingForServletNames(EnumSet.allOf(DispatcherType.class),true,"/*");

	}


	/**
	 * 快速绑定filter 到dispatcher上
	 * @return
	 */
	@Override
	protected Filter[] getServletFilters() {
		CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter("UTF-8",true);
		return  new Filter[]{characterEncodingFilter};

	}

	/**
	 * 实现自定义DispatcherServlet
	 * @param applicationContext
	 * @return
	 */
	@Override
	protected FrameworkServlet createDispatcherServlet(WebApplicationContext applicationContext){
		return super.createDispatcherServlet(applicationContext);
	}
}
